import { computed, ref, Ref, watch } from 'vue';
import { useRouter, useRoute, RouteRecordName } from 'vue-router';
// @ts-ignore
import homeIcon from '../../assets/image/home@2x.png';
// @ts-ignore
import orderIcon from '../../assets/image/order@2x.png';
import { t } from '@/i18n';

// 菜单配置
export const asideList = ref([
    {
        key: '/home/task-list', // 填写路由名称，菜单关联路由
        value: computed(() => t('home.menu.myTask')),
        icon: homeIcon,
    },
    {
        key: '/home/service-list',
        value: computed(() => t('home.menu.taskCenter')),
        icon: orderIcon,
    },
]);

export const routeKey: Ref<RouteRecordName> = ref('');
export const showActiveKey: Ref<RouteRecordName> = ref('');

export function handleSelect(key: string) {
    routeKey.value = key;
}

export function init() {
    const router = useRouter();
    const route = useRoute();

    watch(routeKey, (val, oVal) => {
        if (val !== oVal && asideList.value.some((e) => e.key === val)) {
            router.push({ name: val });
        }
    });

    watch(
        route,
        (val) => {
            let activeMenuKey = '';
            if (typeof val.name === 'string') {
                activeMenuKey = val.name.match(/^\/.+\/.+\//)?.[0].replace(/\/$/, '') || val.name;
            }

            showActiveKey.value = activeMenuKey;
            routeKey.value = val?.name ?? '';
        },
        {
            immediate: true,
        },
    );
}
